<template>
  <el-dialog v-model="visible" :title="title">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="7em">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="用户" prop="user">
        <el-select v-model="form.user" placeholder="选择用户">
          <el-option
            v-for="item in userProfileStore.list"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="区域" prop="areas">
        <city-select v-model="selectCityIds" :multiple="false" emitPath />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="rechargeStore.loading.create || rechargeStore.loading.update"
          @click="handleConfirm"
        >
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { defineModel } from "vue";
import { useRegionalAgentStoreHook } from "@/store/modules/user/regional-agent";
import { useUserProfileStoreHook } from "@/store/modules/user/profile";
import { RegionalAgentForm } from "@/api/user/regionalAgent";
import { cloneDeep } from "lodash-es";

const rechargeStore = useRegionalAgentStoreHook();

const userProfileStore = useUserProfileStoreHook();

export type FormType = "add" | "edit";

export interface Props {
  type: FormType;
  form?: RegionalAgentForm;
}

const visible = defineModel({ type: Boolean, default: false });

const emits = defineEmits(["confirm"]);

const props = defineProps<Props>();

const formRef = ref();

const selectCityIds = ref<number[]>([]);

const defaultForm: RegionalAgentForm = {
  id: undefined,
  name: "",
  user: "",
  province: undefined,
  city: undefined,
  district: undefined,
};

const form = reactive<Partial<RegionalAgentForm>>(cloneDeep(defaultForm));

const rules = {
  name: [
    {
      required: true,
      message: "请输入名称",
      trigger: "change",
    },
  ],
  user: {
    required: true,
    message: "请选择用户",
    trigger: "change",
  },
  areas: [
    {
      required: true,
      message: "请选择区域",
      trigger: "change",
      validator: (rule: any, value: any, callback: any) => {
        if (selectCityIds.value.length === 0) {
          callback(new Error("请选择区域"));
        }
        callback();
      },
    },
  ],
};

const title = computed(() => {
  return props.type === "add" ? "新增" : "编辑";
});

watch(visible, async (val) => {
  if (val) {
    await userProfileStore.fetchUserProfileList({ page: 1, size: 9999 });
    if (props.type === "edit") {
      const idKeys: (keyof RegionalAgentForm)[] = ["province", "city", "district"];
      idKeys.forEach((key) => {
        if (props.form?.[key]) {
          selectCityIds.value.push(props.form?.[key] as number);
        }
      });
      Object.assign(form, props.form);
    }
  } else {
    Object.assign(form, cloneDeep(defaultForm));
    formRef.value.resetFields();
    selectCityIds.value = [];
  }
});

watch(selectCityIds, (val) => {
  console.log(val);
  const [province, city, district] = cloneDeep(val);
  if (province) {
    form.province = province;
  } else {
    form.province = undefined;
  }
  if (city) {
    form.city = city;
  } else {
    form.city = undefined;
  }
  if (district) {
    form.district = district;
  } else {
    form.district = undefined;
  }
});

function handleConfirm() {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (props.type === "add") {
        await rechargeStore.fetchCreate(form);
      } else {
        await rechargeStore.fetchUpdate(form);
      }
      visible.value = false;
      emits("confirm");
    }
  });
}
</script>

<style scoped lang="scss"></style>
